package com.icss.monitor.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icss.monitor.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: Wings丶
 * @Description: 定时器，每隔一段时间就测试esb联通是否正常
 * @Date: Created in 21:50 2018/12/19
 * @Modified By:
 */

@Component
@PropertySource(value = "classpath:application.properties")
public class ConnectifySchedule {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private EmailService emailService;

    @Value("${Svc_Inbound}")
    private String Svc_Inbound;
    @Value("${Svc_ServiceCode}")
    private String Svc_ServiceCode;
    @Value("${Svc_Version}")
    private String Svc_Version;
    @Value("${proxy_Host}")
    private String proxy_Host;
    @Value("${proxy_ServiceUrl}")
    private String proxy_ServiceUrl;



    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//    public final static long ONE_Minute = 60 * 1000;

    @Scheduled(cron = "0 */15 * * * ?")
    public void fixedDelayJob() {
        postByDefault();
    }

    //    @Scheduled(fixedRate=ONE_Minute)
    public void fixedRateJob() {
        System.out.println(formatter.format(new Date()) + " >>fixedRate执行....");
    }

    //    @Scheduled(cron="0 * * * * ?")
    public void cronJob() {
        System.out.println(formatter.format(new Date()) + " >>cron执行....");
    }

    public void postByDefault() {

        String body = null;
        String errorCode = null;
        String url = "http://" + proxy_Host + "/" + proxy_ServiceUrl;
        try {
            errorCode = "000";
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Svc_Inbound", Svc_Inbound);
            headers.add("Svc_ServiceCode", Svc_ServiceCode);
            headers.add("Svc_Version", Svc_Version);
            // 封装参数，千万不要替换为Map与HashMap，否则参数无法传递
            MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
            //添加请求的参数
            requestBody.add("1", "2");

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
            // 执行HTTP请求
            //最后的参数需要用String.class 使用其他的会报错
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            body = response.getBody();
            //模拟数据
//            body = "[{\"appId\":\"ff80808160c10ad20160c4023e47021a\",\"appName\":\"lnsj_安全运维平台\",\"sysCode\":\"\"},{\"appId\":\"ff80808160c10ad20160c402389001b2\",\"appName\":\"lnsj_决策系统\",\"sysCode\":\"ff80808160c10ad20160c402389001b2\"},{\"appId\":\"ff80808160c10ad20160c4023a9201d5\",\"appName\":\"lnsj_数据中心\",\"sysCode\":\"\"},{\"appId\":\"ff80808160c10ad20160c4023d630209\",\"appName\":\"lnsj_烟叶系统\",\"sysCode\":\"\"},{\"appId\":\"ff80808160c10ad20160c4023f34022b\",\"appName\":\"lnsj_市场监管\",\"sysCode\":\"\"},{\"appId\":\"ff80808160c10ad20160d4753e0319d1\",\"appName\":\"lnsj_行业专卖(测试）\",\"sysCode\":\"\"},{\"appId\":\"ff80808160c10ad20160c40239a701c4\",\"appName\":\"lnsj_行业专卖\",\"sysCode\":\"\"},{\"appId\":\"ff80808160c10ad20160c4023c6601f7\",\"appName\":\"lnsj_ESB两级联邦\",\"sysCode\":\"\"},{\"appId\":\"ff80808160c10ad20160c4023b7101e6\",\"appName\":\"lnsj_财务系统\",\"sysCode\":\"ff80808160c10ad20160c4023b7101e6\"}]";
            errorCode = "001";


            JSONArray json = JSONArray.parseArray(body);
            for (Iterator<Object> iterator = json.iterator(); iterator.hasNext(); ) {
                JSONObject job = (JSONObject) iterator.next();
                Set<String> keyIt = job.keySet();
                for (String string : keyIt) {
                    System.out.println(job.get(string));
                }
            }
            errorCode = "002";


        } catch (Exception e) {
            if (errorCode.equals("000")) {
                System.out.println(">>>>>>>>>>>>>>>>>>Service has an error!<<<<<<<<<<<<<<<<<<<<<<");
                this.emailService.sendSimpleEmail("limuhang@chinasofti.com", "ESB系统代理服务调用异常", "服务调用异常");
            } else if (errorCode.equals("001")) {
                System.out.println(">>>>>>>>>>>>>>>>>>Proxy service has an error!<<<<<<<<<<<<<<<<<<<<<<");
                this.emailService.sendSimpleEmail("limuhang@chinasofti.com", "ESB系统代理服务解析异常", "服务解析异常");
            }
        }

        if (errorCode.equals("002")) {
            System.out.println(">>>>>>>>>>>>>>>>>>" + formatter.format(new Date()) + " Service invoke succeeded!<<<<<<<<<<<<<<<<<<<<<<");
        }
    }

}
